/**
 * 是否需要展示 转发按钮
 */
var isShowShareBtn = function(show) {
  if (show) {
    wx.showShareMenu({
      withShareTicket: show
    })
  } else {
    wx.hideShareMenu({

    })
  }
  console.log('当前页面__' + (show ? '可分享' : '不可分享'))
}

/**
 * 检查页面是否 携带参数
 */
var checkPageParameter = function(options) {
  // 二维码 参数
  var scene = decodeURIComponent(options.scene)
  if (scene != "undefined" && scene != null) {
    console.log("二维码中的参数:  " + scene)
    return scene
  }

  // 分享参数
  if (!isEmptyObject(options)) {
    console.log("页面参数:")
    for (var key in options) {
      console.log(key + ":" + options[key]);
    }
    return options;
  } else {
    console.log("页面参数: null")
  }
}

function isEmptyObject(obj) {
  if (JSON.stringify(obj) == '{}') {
    return true;
  } else {
    return false;
  }
}

/**
 * 检查是否 授权 某个权限
 */
var isauthorization = function(authName) {
  if (authName.length == 0) {
    return false;
  }
  wx.getSetting({
    success(res) {
      console.log(res)
      if (res.authSetting[authName]) {
        console.log('用户' + authName + ' 已经授权')
        return true;
      } else {
        console.log('用户信息 ' + authName + '未授权')
        return false;
      }
    },
    fail: function(e) {
      console.log('用户信息 查询失败')
      console.log(e)
      return false;
    }
  })
}

/**
 * 获取用户信息
 */
var getUserInfo = function() {
  const app = getApp()
  var object = app.globalData.userInfo
  if (object == undefined) {
    var userinfo = wx.getStorageSync('userLoginInfo')
    if (userinfo) {
      return userinfo
    } else {
      return ''
    }
  } else {
    return object
  }
}

/**
 * 获取页面dpr和宽度
 */
const getWindowInfo = function() {
  var windowInfo = {};
  windowInfo.dpr = window.devicePixelRatio;
  if (window.innerWidth) {
    windowInfo.width = window.innerWidth;
  } else {
    windowInfo.width = document.body.clientWidth;
  }
  return windowInfo;
}

/**
 * 绘制图片
 * key: 路径字段
 * id:画布 canvas 标识；
 * width: canvas的 宽度
 * height: canvas的 高度
 */
const drawShareImg = function({
  id,
  key,
  width,
  height,
  isdraw,
  fn
}) {
  // wx.showLoading({
  //   title: '正在生成图片...',
  //   mask: true,
  // });
  const ctx = wx.createCanvasContext(id);
  var widthTemp = width || 300
  var heightTemp = height || 500
  var draw = isdraw || false
  fn && fn(ctx);

  return new Promise(function(resolve, reject) {
    ctx.draw(draw, function() {
      setTimeout(function() {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: widthTemp,
          height: heightTemp,
          destWidth: widthTemp * 6,
          destHeight: heightTemp * 6,
          canvasId: id,
          fileType: 'jpg',
          success: function(res) {
            ctx.clearRect(0, 0, widthTemp, heightTemp + 100)
            let iObj = {};
            iObj[key + ''] = res.tempFilePath
            resolve(iObj);
            wx.hideLoading();
          },
          fail: function(res) {
            console.log(res)
            wx.hideLoading();
          }
        })
      }, 200)
    });
  })
}

/**
 * 生成从minNum到maxNum的随机数
 */
var randomNum = function(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      break;
    default:
      return 0;
      break;
  }
}


/**
 *  网络图片 转本地链接
 */
var getFilePath = function(picUrl) {
  return new Promise(function(resolve, reject) {
    wx.downloadFile({
      url: picUrl,
      success: function(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          resolve(res.tempFilePath);
        }
      },
      fail: function(err) {
        console.log(err)
        resolve(picUrl);
      }
    })
  })
}

/**
 * 深拷贝
 * object1  被复制的对象
 * object2  新对象
 * 例子： json2 = common.mutableCopy(json1, json2)
 */
var mutableCopy = function(obj1, obj2) {
  var obj2 = obj2 || {}; //最初的时候给它一个初始值=它自己或者是一个json
  for (var name in obj1) {
    if (typeof obj1[name] === "object") { //先判断一下obj[name]是不是一个对象
      obj2[name] = (obj1[name].constructor === Array) ? [] : {}; //我们让要复制的对象的name项=数组或者是json
      mutableCopy(obj1[name], obj2[name]); //然后来无限调用函数自己 递归思想
    } else {
      obj2[name] = obj1[name]; //如果不是对象，直接等于即可，不会发生引用。
    }
  }
  return obj2; //然后在把复制好的对象给return出去
}

/**
 * 定时  某些清理缓存
 */


/**
 *  获取当前手机 id
 */
var getPhoneModelId = function(model) {
  return new Promise(function(resolve, reject) {
    if (wx.$localStorage.get('phoneModelsList')) {
      forModels(wx.$localStorage.get('phoneModelsList'), model).then(res => {
        res.length > 0 ? resolve(res) : reject(res)
      })
    } else {
      wx.$api.getPhones().then(res => {
        if (res.data.code == 10000) {
          // 保存 手机型号结果
          wx.$localStorage.set('phoneModelsList', res.data.data.phoneInfo)
          forModels(res.data.data.phoneInfo, model).then(res => {
            res.length > 0 ? resolve(res) : reject(res)
          })
        } else {
          reject('')
        }
      })
    }
  })
}

function forModels(phoneModels, model) {
  // 遍历 数据，拿到手机 id字符串
  return new Promise(function(resolve, reject) {
    for (let b = 0; b < phoneModels.length; b++) {
      let brand = phoneModels[b];
      for (let i = 0; i < brand.seriesList.length; i++) {
        let series = brand.seriesList[i];
        for (let j = 0; j < series.modelInfo.length; j++) {
          let phone = series.modelInfo[j];
          if (phone.modelName == model) {
            // "2-1-1-1
            let phoneId = brand.typeId + '-' + series.seriesId + '-' + phone.modelId + '-' + '0'
            return resolve(phoneId)
          }
        }
      }
    }
    return reject('')
  })
}
/**
 *  根据故障名称 获取故障 id
 */
var getPhoneMaintenanceId = function(malfunctionName) {
  return new Promise(function(resolve, reject) {
    if (wx.$localStorage.get('malfunctionList')) {
      let repairInfos = wx.$localStorage.get('malfunctionList');
      for (let i = 0; i < repairInfos.length; i++) {
        let item = repairInfos[i];
        if (item.repairName == malfunctionName) {
          return resolve(item.repairType)
        }
      }
      return reject('1')
    } else {
      // 获取 故障列表
      wx.$api.getMaintenanceList().then(res => {
        if (res.data.code == 10000) {
          wx.$localStorage.set('malfunctionList', res.data.data.repairInfos)
          // 获取故障 id
          for (let i = 0; i < res.data.data.repairInfos.length; i++) {
            let item = res.data.data.repairInfos[i];
            if (item.repairName == malfunctionName) {
              return resolve(item.repairType)
            }
          }
          return reject('1')
        } else {
          reject('1')
        }
      })
    }
  })
}

module.exports = {
  checkPageParameter: checkPageParameter,
  isShowShareBtn: isShowShareBtn,
  isauthorization: isauthorization,
  getUserInfo: getUserInfo,
  drawShareImg: drawShareImg,
  randomNum: randomNum,
  getCloudPath: getFilePath,
  mutableCopy: mutableCopy,
  getPhoneModelId: getPhoneModelId,
  getPhoneMaintenanceId: getPhoneMaintenanceId
}